package com.common.ui.recycleview;

import android.os.Build;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

/**
 * Created by jack
 */

public class RecyclerViewOnScroll extends RecyclerView.OnScrollListener{

    private PullLoadMoreRecyclerView pullLoadMoreRecyclerView;

    public RecyclerViewOnScroll(PullLoadMoreRecyclerView pullLoadMoreRecyclerView) {
        this.pullLoadMoreRecyclerView = pullLoadMoreRecyclerView;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        int lastItem = 0;
        int firstItem = 0;
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        //对于item的总数量很好获取直接调用
        //int totalItemCount = layoutManager.getItemCount();
        //RecyclerView能实现LinearLayoutManager、GridLayoutManager与StaggeredGridLayoutManager不同的布局
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager gridLayoutManager = ((GridLayoutManager) layoutManager);
            firstItem = gridLayoutManager.findFirstCompletelyVisibleItemPosition();
            //Position to find the final item of the current LayoutManager
            lastItem = gridLayoutManager.findLastCompletelyVisibleItemPosition();
            if (lastItem == -1){
                lastItem = gridLayoutManager.findLastVisibleItemPosition();
            }
        }else if (layoutManager instanceof LinearLayoutManager) {
            LinearLayoutManager linearLayoutManager = ((LinearLayoutManager) layoutManager);
            firstItem = linearLayoutManager.findFirstCompletelyVisibleItemPosition();
            lastItem = linearLayoutManager.findLastCompletelyVisibleItemPosition();
            if (lastItem == -1){
                lastItem = linearLayoutManager.findLastVisibleItemPosition();
            }
        }else if (layoutManager instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager staggeredGridLayoutManager
                    = ((StaggeredGridLayoutManager) layoutManager);
            // since may lead to the final item has more than one StaggeredGridLayoutManager the particularity of the so here that is an array
            // this array into an array of position and then take the maximum value that is the last show the position value
            int[] lastPositions = new int[((StaggeredGridLayoutManager) layoutManager).getSpanCount()];
            staggeredGridLayoutManager.findLastCompletelyVisibleItemPositions(lastPositions);
            lastItem = findMax(lastPositions);
            firstItem = staggeredGridLayoutManager.findFirstVisibleItemPositions(lastPositions)[0];
        }

        if(pullLoadMoreRecyclerView.isPushRefreshEnable()
                && !pullLoadMoreRecyclerView.isRefreshing()
                && pullLoadMoreRecyclerView.getFooterState()!=3
                &&isScrollToBottom()){
            pullLoadMoreRecyclerView.loadMore();
        }
    }

    //To find the maximum value in the array
    private int findMax(int[] lastPositions) {
        int max = lastPositions[0];
        for (int value : lastPositions) {
            if (value > max) {
                max = value;
            }
        }
        return max;
    }

    /**
     * 是否滑动到底部
     *
     * @return
     */
    public boolean isScrollToBottom() {

        boolean toTop = isScrollToTop();
        if(toTop){
            return false;
        }
        RecyclerView recyclerView = pullLoadMoreRecyclerView.getRecyclerView();
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        int count = recyclerView.getAdapter().getItemCount();
        if (layoutManager instanceof LinearLayoutManager && count > 0) {
            LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager;
            if (linearLayoutManager.findLastCompletelyVisibleItemPosition() == count - 1) {
                return true;
            }
        }
        /**
         * GridLayoutManager可以用StaggeredGridLayoutManager代替使用
         */
//            else if(layoutManager instanceof GridLayoutManager && count > 0){
//                //GridLayoutManager gridLayoutManager = (GridLayoutManager) layoutManager;
//            }
        else if (layoutManager instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) layoutManager;
            int[] lastItems = new int[2];
            staggeredGridLayoutManager
                    .findLastCompletelyVisibleItemPositions(lastItems);
            int lastItem = Math.max(lastItems[0], lastItems[1]);
            if (lastItem == count - 1) {
                return true;
            }
        }
        return false;
    }

    public boolean isScrollToTop() {
        if (Build.VERSION.SDK_INT < 14) {
            return !(pullLoadMoreRecyclerView.getRecyclerView().getScrollY() > 0);
        } else {
            /**
             * 用来判断view在竖直方向上能不能向上或者向下滑动
             * @param view v
             * @param direction 方向    负数代表向上滑动 ，正数则反之
             * @return
             */
            return !ViewCompat.canScrollVertically(pullLoadMoreRecyclerView.getRecyclerView(), -1);
        }
    }
}
